package cn.ulyer.common.oauth;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import net.minidev.json.annotate.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Data
public class OauthClient implements ClientDetails {

    final static String SPLIT = ",";

    private String clientId;

    private String resourceIds;

    @JsonIgnore
    private String clientSecret;

    private String redirectUrls;

    private String scope;

    private String grantTypes;

    private Integer accessTokenValidSeconds;

    private Integer refreshTokenValidSeconds;

    private String additionalInfo;

    private Set<GrantedAuthority> authorities;

    @Override
    public String getClientId() {
        return clientId;
    }

    @Override
    public Set<String> getResourceIds() {
        return (Set<String>) CollectionUtil.addAll(new HashSet<>(),StringUtils.split(resourceIds,SPLIT));
    }

    @Override
    public boolean isSecretRequired() {
        return true;
    }

    @Override
    public String getClientSecret() {
        return clientSecret;
    }

    @Override
    public boolean isScoped() {
        return true;
    }

    /**
     * oauth2的权限概念
     * @return
     */
    @Override
    public Set<String> getScope() {
        return (Set<String>) CollectionUtil.addAll(new HashSet<>(),StringUtils.split(scope,SPLIT));
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return (Set<String>) CollectionUtil.addAll(new HashSet<>(),StringUtils.split(grantTypes,SPLIT));
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {
        return (Set<String>) CollectionUtil.addAll(new HashSet<>(),StringUtils.split(redirectUrls,SPLIT));
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return CollectionUtil.addAll(new HashSet<>(),authorities);
    }

    @Override
    public Integer getAccessTokenValiditySeconds() {
        return accessTokenValidSeconds;
    }

    @Override
    public Integer getRefreshTokenValiditySeconds() {
        return refreshTokenValidSeconds;
    }

    @Override
    public boolean isAutoApprove(String s) {
        return false;
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        return StringUtils.isBlank(additionalInfo) ? null : JSONObject.parseObject(additionalInfo);
    }

}

